package models

import (
	"github.com/astaxie/beego/orm"
	"strconv"
	"strings"
)

func BaseCreate(obj interface{}) (err error) {
	o := GetDefaultDB()
	_, err = o.Insert(obj)
	return
}

func BaseGetById(obj interface{}) (err error) {
	o := GetReadDB()
	orm.Debug = false
	err = o.Read(obj)
	orm.Debug = true
	return
}

func BaseUpdate(obj interface{}, param ...string) (num int64, err error) {
	o := GetDefaultDB()
	num, err = o.Update(obj, param...)
	return
}

func BaseDelete(obj interface{}) (err error) {
	o := GetDefaultDB()
	_, err = o.Delete(obj)
	return
}

func GetReadDB() orm.Ormer {
	o := orm.NewOrm()
	err := o.Using("read")
	if err != nil {
		o.Using("default")
	}
	return o
}

func GetDefaultDB() orm.Ormer {
	o := orm.NewOrm()
	err := o.Using("default")
	if err != nil {
		panic(err)
	}
	return o
}

func ContainIds(ids, id string) bool {
	if len(ids) == 0 || len(id) == 0 {
		return false
	}
	i, err := strconv.Atoi(id)

	if i == 0 || err != nil {
		return false
	}
	for _, s := range strings.Split(ids, ",") {
		sid, _ := strconv.Atoi(s)
		if sid == i {
			return true
		}
	}
	return false
}
